<template>
  <!-- 主容器 - 基于样式参考的米白色背景 -->
  <div class="min-h-screen flex flex-col" style="background-color: #FAF9F5;">
    <!-- 顶部品牌区域 -->
    <div class="flex-shrink-0 pt-12 pb-8">
      <div class="text-center">
        <!-- 加利顿大学 Logo -->
        <div class="flex items-center justify-center" style="gap: 2px;">
          <img 
            src="/src/assets/imgs/logo.png" 
            alt="加利顿大学 Logo" 
            class="flex-shrink-0" 
            style="width: 39.5px; height: 39.5px; background-color: #D97757; border-radius: 50%; padding: 4px; box-sizing: border-box;"
          />
          <h3 class="text-gray-900 text-xl font-semibold leading-none select-none">
            加利顿大学
          </h3>
        </div>
        <!-- 主标题 -->
        <h1 class="text-center text-gray-900 font-display mt-4 min-[500px]:text-[3.5rem] min-[350px]:text-[3.2rem] text-[1.75rem] [&_span]:[backface-visibility:hidden] select-none [font-feature-settings:'liga'_1] leading-tight">
          新生报到服务平台
        </h1>
      </div>
    </div>
    
    <!-- 登录卡片容器 - 垂直水平居中 -->
    <div class="flex-1 flex items-center justify-center px-4 pb-12">
      <div class="w-full max-w-sm">
        <!-- 登录卡片 -->
        <div class="border border-gray-200 rounded-lg p-8" style="background-color: #FAF9F5; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);">
          <!-- 登录类型切换 -->
          <div class="flex rounded-lg p-1 mb-8" style="background-color: #F5F5F0;">
            <button
              @click="switchLoginType('admin')"
              :class="[
                'flex-1 py-2.5 px-4 text-sm font-medium rounded-md transition-all duration-200',
                loginType === 'admin' 
                  ? 'text-gray-900 shadow-sm border border-gray-300' 
                  : 'text-gray-600 hover:text-gray-900'
              ]"
              :style="loginType === 'admin' ? 'background-color: #FAF9F5;' : ''"
            >
              <i class="icon-[heroicons--shield-check] w-4 h-4 mr-2 inline"></i>
              管理员登录
            </button>
            <button
              @click="switchLoginType('student')"
              :class="[
                'flex-1 py-2.5 px-4 text-sm font-medium rounded-md transition-all duration-200',
                loginType === 'student' 
                  ? 'text-gray-900 shadow-sm border border-gray-300' 
                  : 'text-gray-600 hover:text-gray-900'
              ]"
              :style="loginType === 'student' ? 'background-color: #FAF9F5;' : ''"
            >
              <i class="icon-[heroicons--user-group] w-4 h-4 mr-2 inline"></i>
              学生登录
            </button>
          </div>

          <!-- 卡片头部 -->
          <div class="text-center mb-8">
            <h2 class="text-xl font-semibold text-gray-900 mb-2">
              {{ loginType === 'admin' ? '管理员登录' : '学生登录' }}
            </h2>
            <p class="text-sm text-gray-600">
              {{ loginType === 'admin' ? '请输入管理员账号和密码' : '请输入学生账号和密码' }}
            </p>
          </div>
          
          <!-- 登录表单 -->
          <form @submit.prevent="handleLogin" class="space-y-6 flex-1 flex flex-col">
            <!-- 表单字段容器 -->
            <div class="flex-1 space-y-6">
              <!-- 统一登录表单 -->
              <!-- 用户名输入框 -->
              <div>
                <label for="username" class="block text-sm font-medium text-gray-700 mb-2">
                  用户名
                </label>
                <div class="relative">
                  <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <i class="icon-[heroicons--user] w-5 h-5 text-gray-400"></i>
                  </div>
                  <input
                    id="username"
                    v-model="form.username"
                    type="text"
                    required
                    :class="[
                      'border border-gray-300 hover:border-gray-400 transition-colors placeholder:text-gray-500 focus:outline-none focus:ring-1 focus:ring-gray-400 focus:border-gray-400 disabled:cursor-not-allowed disabled:opacity-50 h-11 px-3 rounded-[0.6rem] w-full pl-10',
                      errors.username ? 'border-red-500 focus:border-red-500 focus:ring-red-500' : ''
                    ]"
                    style="background-color: #FAF9F5;"
                    placeholder="请输入用户名"
                    :disabled="loading"
                  >
                </div>
                <p v-if="errors.username" class="mt-1 text-sm text-red-600">
                  {{ errors.username }}
                </p>
              </div>
              
              <!-- 密码输入框 -->
              <div>
                <label for="password" class="block text-sm font-medium text-gray-700 mb-2">
                  密码
                </label>
                <div class="relative">
                  <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <i class="icon-[heroicons--lock-closed] w-5 h-5 text-gray-400"></i>
                  </div>
                  <input
                    id="password"
                    v-model="form.password"
                    :type="showPassword ? 'text' : 'password'"
                    required
                    :class="[
                      'border border-gray-300 hover:border-gray-400 transition-colors placeholder:text-gray-500 focus:outline-none focus:ring-1 focus:ring-gray-400 focus:border-gray-400 disabled:cursor-not-allowed disabled:opacity-50 h-11 px-3 rounded-[0.6rem] w-full pl-10 pr-10',
                      errors.password ? 'border-red-500 focus:border-red-500 focus:ring-red-500' : ''
                    ]"
                    style="background-color: #FAF9F5;"
                    placeholder="请输入密码"
                    :disabled="loading"
                  >
                  <button
                    type="button"
                    @click="togglePassword"
                    class="absolute inset-y-0 right-0 pr-3 flex items-center"
                    :disabled="loading"
                  >
                    <i 
                      :class="[
                        showPassword ? 'icon-[heroicons--eye-slash]' : 'icon-[heroicons--eye]',
                        'w-5 h-5 text-gray-400 hover:text-gray-600'
                      ]"
                    ></i>
                  </button>
                </div>
                <p v-if="errors.password" class="mt-1 text-sm text-red-600">
                  {{ errors.password }}
                </p>
              </div>



              <!-- 记住密码和忘记密码 -->
              <div class="flex items-center justify-between">
                <div class="flex items-center">
                  <input
                    id="remember"
                    v-model="form.remember"
                    type="checkbox"
                    class="h-4 w-4 text-gray-600 focus:ring-gray-400 border-gray-300 rounded"
                    :disabled="loading"
                  >
                  <label for="remember" class="ml-2 block text-sm text-gray-600">
                    记住密码
                  </label>
                </div>
                
                <button
                  type="button"
                  class="text-sm text-gray-600 hover:text-gray-800 transition-colors"
                  :disabled="loading"
                  @click="handleForgotPassword"
                >
                  忘记密码？
                </button>
              </div>
            </div>
            
            <!-- 表单底部区域 -->
            <div class="space-y-4">
              <!-- 登录按钮 -->
              <button
                type="submit"
                :disabled="loading"
                class="inline-flex items-center justify-center relative shrink-0 select-none disabled:pointer-events-none disabled:opacity-50 disabled:shadow-none disabled:drop-shadow-none text-gray-900 font-semibold border border-gray-300 relative overflow-hidden transition duration-100 hover:border-gray-400 hover:bg-gray-100 h-11 rounded-[0.6rem] px-5 min-w-[6rem] active:scale-[0.985] whitespace-nowrap text-base w-full gap-2"
                style="background-color: #FAF9F5;"
              >
                <div v-if="loading" class="flex items-center justify-center">
                  <div class="loading-spinner mr-2"></div>
                  登录中...
                </div>
                <span v-else>登录</span>
              </button>
              
              <!-- 错误提示 -->
              <div v-if="loginError" class="p-3 bg-red-50 border border-red-200 rounded-lg">
                <div class="flex items-center">
                  <i class="icon-[heroicons--exclamation-triangle] w-5 h-5 text-red-400 mr-2"></i>
                  <span class="text-sm text-red-700">{{ loginError }}</span>
                </div>
              </div>
            </div>
          </form>
          
          <!-- 联系我们 -->
          <div class="mt-8 text-center">
            <button
              @click="showContactModal = true"
              class="text-sm text-gray-600 hover:text-gray-800 transition-colors"
            >
              <i class="icon-[heroicons--phone] w-4 h-4 mr-1 inline"></i>
              联系我们
            </button>
          </div>
        </div>
        
        <!-- 底部版权信息 -->
        <div class="mt-8 text-center text-sm text-gray-500">
          <p>Copyright © 2024 新生报到服务平台</p>
          <p class="mt-1">Powered by Vue 3 + Tailwind CSS</p>
        </div>
      </div>
    </div>

    <!-- 联系我们弹窗 -->
    <div v-if="showContactModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
      <div class="bg-white rounded-lg p-6 w-full max-w-sm">
        <div class="text-center mb-4">
          <h3 class="text-lg font-semibold text-gray-900">联系我们</h3>
        </div>
        
        <div class="space-y-4">
          <div class="flex items-center space-x-3">
            <i class="icon-[heroicons--phone] w-5 h-5 text-blue-500"></i>
            <div>
              <p class="text-sm font-medium text-gray-900">招生办电话</p>
              <p class="text-sm text-gray-600">400-123-4567</p>
            </div>
          </div>
          
          <div class="flex items-center space-x-3">
            <i class="icon-[heroicons--envelope] w-5 h-5 text-blue-500"></i>
            <div>
              <p class="text-sm font-medium text-gray-900">邮箱地址</p>
              <p class="text-sm text-gray-600">admission@university.edu.cn</p>
            </div>
          </div>
          
          <div class="flex items-center space-x-3">
            <i class="icon-[heroicons--clock] w-5 h-5 text-blue-500"></i>
            <div>
              <p class="text-sm font-medium text-gray-900">服务时间</p>
              <p class="text-sm text-gray-600">周一至周日 8:00-18:00</p>
            </div>
          </div>
        </div>
        
        <div class="mt-6">
          <button
            @click="showContactModal = false"
            class="inline-flex items-center justify-center rounded-lg px-4 py-2 text-sm font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed bg-blue-500 text-white hover:bg-blue-600 focus:ring-blue-500 w-full"
          >
            知道了
          </button>
        </div>
      </div>
    </div>
  </div>

</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { useAppStore } from '../stores/app'

// 使用stores和路由
const authStore = useAuthStore()
const appStore = useAppStore()
const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const showPassword = ref(false)
const loginError = ref('')
const loginType = ref('student') // 'admin' | 'student'
const showContactModal = ref(false)

// 表单数据
const form = reactive({
  username: '',
  password: '',
  remember: false
})

// 表单验证错误
const errors = reactive({
  username: '',
  password: ''
})

// 方法
const switchLoginType = (type) => {
  loginType.value = type
  loginError.value = ''
  // 清空表单错误
  Object.keys(errors).forEach(key => {
    errors[key] = ''
  })
}

const togglePassword = () => {
  showPassword.value = !showPassword.value
}

const validateForm = () => {
  errors.username = ''
  errors.password = ''
  
  if (!form.username.trim()) {
    errors.username = '请输入用户名'
    return false
  }
  
  if (!form.password.trim()) {
    errors.password = '请输入密码'
    return false
  }
  
  if (form.password.length < 6) {
    errors.password = '密码长度不能少于6位'
    return false
  }
  
  return true
}

const handleLogin = async () => {
  if (!validateForm()) {
    console.log('🚫 表单验证失败')
    return
  }
  
  loading.value = true
  loginError.value = ''
  
  try {
    // 构建请求数据
    const loginData = {
      username: form.username,
      password: form.password,
      role: loginType.value === 'admin' ? 0 : 1  // 0是admin，1是student
    }
    
    console.log('🚀 开始登录请求')
    console.log('📝 登录类型:', loginType.value)
    console.log('📝 请求数据:', loginData)
    
    // 调用登录API
    const result = await authStore.login(loginData)
    
    console.log('📥 API响应结果:', result)
     
     // 检查响应格式 - 后端成功返回code为1，失败返回code为0
     if (result && result.code === 1) {
       console.log('✅ 登录成功! (code: 1)')
       console.log('📄 响应数据:', result.data)
       console.log('🔑 Token:', result.data?.token)
       console.log('👤 用户信息:', {
         userId: result.data?.userId,
         username: result.data?.username,
         role: result.data?.role
       })
       
       appStore.showSuccess(result.msg || '登录成功！')
       
       // 根据角色跳转
       if (loginType.value === 'admin') {
         console.log('🔄 跳转到管理员面板')
         router.push('/admin/dashboard')
       } else {
         console.log('🔄 跳转到学生主页')
         router.push('/student/home')
       }
     } else if (result && result.code === 0) {
       console.log('❌ 登录失败! (code: 0)')
       console.log('📄 失败响应:', result)
       console.log('💬 失败消息:', result.msg)
       loginError.value = result?.msg || '登录失败，请检查用户名和密码'
     } else {
       console.log('❓ 未知响应格式!')
       console.log('📄 响应内容:', result)
       loginError.value = '服务器响应格式异常，请稍后重试'
     }
  } catch (error) {
    console.error('💥 登录异常:', error)
    console.error('📄 错误详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status
    })
    
    // 处理不同类型的错误
    if (error.response) {
      // 服务器响应了错误状态码
      const errorData = error.response.data
      console.log('🔍 服务器错误响应:', errorData)
      loginError.value = errorData?.msg || errorData?.message || '服务器错误，请稍后重试'
    } else if (error.request) {
      // 请求已发出但没有收到响应
      console.log('🔍 网络错误，无响应')
      loginError.value = '网络连接失败，请检查网络连接'
    } else {
      // 其他错误
      console.log('🔍 其他错误:', error.message)
      loginError.value = '登录失败，请稍后重试'
    }
  } finally {
    loading.value = false
    console.log('🏁 登录流程结束')
  }
}

const handleForgotPassword = () => {
  appStore.showInfo('请联系系统管理员重置密码')
}

// 生命周期
onMounted(() => {
  // 设置页面标题
  appStore.setPageTitle('统一登录')
  
  // 根据路由参数设置登录类型
  if (route.query.type === 'admin') {
    loginType.value = 'admin'
  } else if (route.query.type === 'student') {
    loginType.value = 'student'
  }
  
  // 开发环境下预填充表单（可选）
  if (import.meta.env.DEV) {
    if (loginType.value === 'admin') {
      form.username = 'admin'
      form.password = '123456'
    } else {
      form.username = 'student001'
      form.password = '123456'
    }
  }
})
</script>

<style scoped>
/* 组件特定样式 */
.gradient-bg {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

/* 加载动画 */
.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid #ffffff;
  border-top: 2px solid transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 动画效果 */
.card {
  animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 装饰元素动画 */
.absolute.top-20 {
  animation: float 6s ease-in-out infinite;
}

.absolute.top-40 {
  animation: float 8s ease-in-out infinite reverse;
}

.absolute.bottom-32 {
  animation: float 7s ease-in-out infinite;
}

.absolute.bottom-20 {
  animation: float 5s ease-in-out infinite reverse;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-20px);
  }
}

/* 弹窗动画 */
.fixed.inset-0 {
  animation: fadeIn 0.3s ease-out;
}

.fixed.inset-0 > div {
  animation: scaleIn 0.3s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes scaleIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}
</style>